<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015/7/31
 * Time: 11:04
 */

namespace p5\objects;


use ReflectionClass;

class BeanUtils
{
    public static function reflectPropertyToArray($object)
    {
        $reflect = new ReflectionClass($object);
        $props = $reflect->getProperties(); //ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PRIVATE | ReflectionProperty::IS_PROTECTED
        $matrix = [];
        foreach ($props as $prop) {
            $prop->setAccessible(true); //不使用setAccessible则会报错
            $matrix[$prop->getName()] = $prop->getValue($object);
        }
        return $matrix;
    }

    public static function setProperties($object, $properties)
    {
        if (empty($properties)) {
            return;
        }
        if (!is_array($properties)) {
            return;
        }
        foreach ($properties as $key => $value) {
            $method = "set_" . $key;
            $b = self::setProperty($object, $method, $value);
            if ($b) {
                continue;
            }
            $method = "set" . StringUtils::camel_case($key);
            $b = self::setProperty($object, $method, $value);
        }
    }

    public static function setProperty($object, $method, $value)
    {
        if (method_exists($object, $method)) {
            try {
                $object->$method($value);
                return true;
            } catch (\Exception $e) {
                // do nothing
            }
        }
        return false;
    }

    public static function getProperty($object, $name, $defaultValue = "")
    {
        try {
            $methods = ["get_" . $name, "get" . ucfirst(StringUtils::camel_case($name))];
            for ($i = 0; $i < count($methods); $i++) {
                $method = $methods[$i];
                if (method_exists($object, $method)) {
                    return $object->$method();
                }
            }
            // 无法获取到属性，尝试转化成数组形式
            if (is_object($object)) {
                $string = json_encode($object);
                $array = json_decode($string, true);
                if (array_key_exists($name, $array)) {
                    return $array[$name];
                } else {
                    return $defaultValue;
                }
            }
            return $defaultValue;
        } catch (\Exception $e) {
            return $defaultValue;
        }
    }
}